var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var isSecondSubmit = false;

Page({
  data: {
    id: 0,
    pids: {},
    goods: {},
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartGoodsCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedPic: '',
    checkedSpecText: '规格数量选择',
    tmpSpecText: '请选择规格数量',
    checkedSpecPriceFlag: '',
    checkedSpecPrice: 0,
    priceCoinFlag: '',
    priceCoin: 0,
    remindValue: ['', '', '送'],
    plusFlag: ['', '+', '  '],
    openAttr: false,
    noCollectImage: '/static/images/icon_collect.png',
    // noCollectImage: '/static/images/icon_ evaluation.png',
    hasCollectImage: '/static/images/icon_collect_checked_full.png',
    // hasCollectImage: '/static/images/icon_ evaluation_checked.png',

    collectImage: '/static/images/icon_collect.png',
    // collectImage: '/static/images/icon_ evaluation.png',
    soldout: false,
    disabled: false,
    dis: true,
    text: '\n',
    color:[],
    memberType: false,
    mobile:''
  },
  formSubmit_collect: function (e) {
    let formId = e.detail.formId;
    // console.log('form发生了submit事件，推送码为：', formId)
  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    // this.getGoodsInfo();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getGoodsInfo: function() {
    let that = this;
    util.request(api.GoodsDetail, {
      id: that.data.id
    }).then(function(res) {
      if (res.errno === 0) {

        let _specificationList = res.data.specificationList
        // 如果仅仅存在一种货品，那么商品页面初始化时默认checked
        if (_specificationList.length == 1) {
          if (_specificationList[0].valueList.length == 1) {
            _specificationList[0].valueList[0].checked = true
            
            // 如果仅仅存在一种货品，那么商品价格应该和货品价格一致
            // 这里检测一下
            let _productPrice = res.data.productList[0].price;
            let _goodsPrice = res.data.info.retailPrice;
            if (_productPrice != _goodsPrice) {
              console.error('商品数量价格和货品不一致');
            }

            that.setData({
              checkedSpecText: _specificationList[0].valueList[0].value,
              tmpSpecText: '已选择：' + _specificationList[0].valueList[0].value,
            });
          }
        }
        if (res.data.brand == null) {
          res.data.brand = ''
        }
        if (res.data.pids == null) {
          res.data.pids = ''
        }

        that.setData({
          pids: res.data.pids,
          goods: res.data.info,
          checkedPic: res.data.info.picUrl,
          attribute: res.data.attribute,
          issueList: res.data.issue,
          comment: res.data.comment,
          brand: res.data.brand,
          specificationList: res.data.specificationList,
          productList: res.data.productList,
          userHasCollect: res.data.userHasCollect,
          //积分扣赠标志 1代表扣除 2代表赠送
          checkedSpecPriceFlag: res.data.info.integralFlag,
          //积分
          checkedSpecPrice: res.data.info.integral,
          //爱币扣赠标志 1代表扣除 2代表赠送
          priceCoinFlag: res.data.info.priceFlag,
          //爱币
          priceCoin: res.data.info.retailPrice,
          mobile:res.data.mobile
        });
        // console.log(res.data.mobile);

        if (res.data.userHasCollect == 1) {
          that.setData({
            collectImage: that.data.hasCollectImage
          });
        } else {
          that.setData({
            collectImage: that.data.noCollectImage
          });
        }

        WxParse.wxParse('goodsDetail', 'html', res.data.info.desc, that);

        that.getGoodsRelated();
      }
    });

  },
  getGoodsRelated: function() {
    let that = this;
    util.request(api.GoodsRelated, {
      id: that.data.id
    }).then(function(res) {
      if (res.errno === 0) {
        that.setData({
          relatedGoods: res.data.goodsList,
        });
      }
    });

  },
  clickSkuValue: function(event) {
    let that = this;
    let specName = event.currentTarget.dataset.name;
    let specValueId = event.currentTarget.dataset.valueId;

    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      if (_specificationList[i].name === specName) {
        for (let j = 0; j < _specificationList[i].valueList.length; j++) {
          if (_specificationList[i].valueList[j].id == specValueId) {
            //如果已经选中，则反选
            if (_specificationList[i].valueList[j].checked) {
              _specificationList[i].valueList[j].checked = false;
            } else {
              _specificationList[i].valueList[j].checked = true;
            }
          } else {
            _specificationList[i].valueList[j].checked = false;
          }
        }
      }
    }
    this.setData({
      specificationList: _specificationList,
    });
    //重新计算spec改变后的信息
    this.changeSpecInfo();

    //重新计算哪些值不可以点击
  },
  //获取选中的规格信息
  getCheckedSpecValue: function() {
    let checkedValues = [];
    let _specificationList = this.data.specificationList;
    for (let i = 0; i < _specificationList.length; i++) {
      let _checkedObj = {
        name: _specificationList[i].name,
        valueId: 0,
        valueText: ''
      };
      for (let j = 0; j < _specificationList[i].valueList.length; j++) {
        if (_specificationList[i].valueList[j].checked) {
          _checkedObj.valueId = _specificationList[i].valueList[j].id;
          _checkedObj.valueText = _specificationList[i].valueList[j].value;
        }
      }
      checkedValues.push(_checkedObj);
    }

    return checkedValues;
  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function() {

  },
  //判断规格是否选择完整
  isCheckedAllSpec: function() {
    return !this.getCheckedSpecValue().some(function(v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedSpecKey: function() {
    let checkedValue = this.getCheckedSpecValue().map(function(v) {
      return v.valueText;
    });

    return checkedValue;
  },
  changeSpecInfo: function() {
    let checkedNameValue = this.getCheckedSpecValue();
    
    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function(v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function(v) {
      return v.valueText;
    });
    if (checkedValue.length > 0) {
      this.setData({
        tmpSpecText: checkedValue.join('　')
      });
    } else {
      this.setData({
        tmpSpecText: '请选择规格数量'
      });
    }


    if (this.isCheckedAllSpec()) {
      this.setData({
        checkedSpecText: this.data.tmpSpecText
      });

      // 规格所对应的货品选择以后
      let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProductArray || checkedProductArray.length <= 0) {
        this.setData({
          soldout: true
        });
        console.error('规格所对应货品不存在');
        return;
      }

      let checkedProduct = checkedProductArray[0];
      if (checkedProduct.number > 0) {
        this.setData({
          checkedPic: checkedProduct.url,
          priceCoin: checkedProduct.price,
          priceCoinFlag: checkedProduct.priceFlag,
          checkedSpecPrice: checkedProduct.integral,
          checkedSpecPriceFlag: checkedProduct.integralFlag,
          soldout: false
        });
      } else {
        this.setData({
          checkedSpecPrice: this.data.goods.integral,
          checkedSpecPriceFlag: this.data.goods.integralFlag,
          priceCoin: this.data.goods.price,
          priceCoinFlag: this.data.goods.priceFlag,
          soldout: true
        });
      }

    } else {
      this.setData({
        checkedSpecText: '规格数量选择',
        checkedSpecPrice: this.data.goods.integral,
        checkedSpecPriceFlag: this.data.goods.integralFlag,
        priceCoin: this.data.goods.price,
        priceCoinFlag: this.data.goods.priceFlag,
        soldout: false
      });
    }

  },
  getCheckedProductItem: function(key) {
    return this.data.productList.filter(function(v) {
      if (v.specifications.toString() == key.toString()) {
        return true;
      } else {
        return false;
      }
    });
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      id: parseInt(options.id)
    });
    this.getGoodsInfo();

  },
  onReady: function() {
    // 页面渲染完成

  },
  onShow: function() {
    // 页面显示
    var that = this;
    // util.request(api.CartGoodsCount).then(function(res) {
    //   if (res.errno === 0) {
    //     that.setData({
    //       cartGoodsCount: res.data
    //     });
    //   }
    // });
    let cartGoodsCount = 0;
    var arr = wx.getStorageSync('cart')
    for (var i = 0; i < arr.length; i++) {
      cartGoodsCount += arr[i].number
    }
    that.setData({
      cartGoodsCount: cartGoodsCount
        });

    util.request(api.UserMemberType).then(function (res) {
      if (res.data.hasLogin==true){
        var memberType = res.data.MemberType
        // console.log(memberType + "mm")
        that.setData({
          memberType: memberType
        })
      }else{
        var memberType = wx.getStorageSync("memberType");
        if (memberType==true){
          that.setData({
            memberType: memberType
          })
        }
      }
      
    })
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },
  switchAttrPop: function() {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr,
        dis: true     
      });
    }
  },
  closeAttr: function() {
    let that = this;
    that.setData({
      openAttr: false,
      disabled: false,
      color: ''
    });
  },
  addCollectOrNot: function() {
    let that = this;
    //添加或是取消收藏
    util.request(api.CollectAddOrDelete, {
        type: 0,
        valueId: this.data.id
      }, "POST")
      .then(function(res) {
        let _res = res;
        if (_res.errno == 0) {
          if (_res.data.type == 'add') {
            that.setData({
              collectImage: that.data.hasCollectImage
            });
          } else {
            that.setData({
              collectImage: that.data.noCollectImage
            });
          }
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: _res.errmsg,
            mask: true
          });
        }

      });

  },
  openCartPage: function() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },
  addFast: function() {
    let categoryId = this.data.goods.categoryId
    var pids = app.globalData.memberGoodsNum
    if (pids.indexOf(categoryId) != -1){
      if (app.globalData.hasLogin == false){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
      }else{
        
        var memberType = this.data.memberType;
        
      
      if (memberType == true) {
        if (isSecondSubmit == false) {
          isSecondSubmit = true;
          var that = this;
          if (this.data.openAttr == false) {
            //打开规格选择窗口
            this.setData({
              openAttr: !this.data.openAttr,
              disabled: false,
              dis: true,
            });
          } else {
            isSecondSubmit = false;
            //提示选择完整规格
            if (!this.isCheckedAllSpec()) {
              wx.showToast({
                image: '/static/images/icon_error.png',
                title: '请选择完整规格'
              });
              this.setData({
                openAttr: !this.data.openAttr,
                disabled: false,
                dis: true,
              });
              return false;
            }
            //根据选中的规格，判断是否有对应的sku信息
            let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
            if (!checkedProductArray || checkedProductArray.length <= 0) {
              //找不到对应的product信息，提示没有库存
              wx.showToast({
                image: '/static/images/icon_error.png',
                title: '没有库存'
              });
              return false;
            }

            let checkedProduct = checkedProductArray[0];
            //验证库存
            if (checkedProduct.number <= 0) {
              wx.showToast({
                image: '/static/images/icon_error.png',
                title: '没有库存'
              });
              return false;
            } else if (checkedProduct.number < this.data.number) {
              wx.showToast({
                image: '/static/images/icon_error.png',
                title: '库存不足'
              });
              return false;
            }
            //立即购买
            let data = [];
            var goods = this.data.goods;
            goods.isSelect = false;
            var goodsId = this.data.goods.id;
            //添加的商品数量
            var goodsnumber = this.data.number;
            goods.number = goodsnumber;
            var productId = checkedProduct.id;
            var name = this.data.goods.name;
            goods.productId = productId
            // 积分
            goods.integral = checkedProduct.integral
            goods.retailPrice = checkedProduct.price
            goods.priceFlag = checkedProduct.priceFlag
            goods.goodsName = name;

            goods.specifications = this.data.checkedSpecText
            goods.checked = true
            if (name.length > 22) {
              goods.goodsName = name.substring(0, 22) + '...';
            }

            wx.setStorageSync('cartflag', 1);
            data.push(goods);
            wx.setStorageSync('cartOne', data)
            try {
              // wx.setStorageSync('cartId', res.data);
              if (app.globalData.hasLogin) {
                if (this.data.mobile == "" || this.data.mobile == undefined) {
                  wx.redirectTo({
                    url: "/pages/auth/bindMobile/bindMobile"
                  });
                } else {
                  wx.navigateTo({
                    url: '/pages/checkout/checkout'
                  })
                }
              } else {
                wx.navigateTo({
                  url: "/pages/auth/login/login"
                });
              }
            } catch (e) { }


            // util.request(api.CartFastAdd, {
            //     goodsId: this.data.goods.id,
            //     number: this.data.number,
            //     productId: checkedProduct.id
            //   }, "POST")
            //   .then(function(res) {
            //     if (res.errno == 0) {

            //       // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
            //       try {
            //         wx.setStorageSync('cartId', res.data);
            //         wx.navigateTo({
            //           url: '/pages/checkout/checkout'
            //         })
            //       } catch (e) {}

            //     } else {
            //       wx.showToast({
            //         image: '/static/images/icon_error.png',
            //         title: res.errmsg,
            //         mask: true
            //       });
            //     }
            //   });
          }
          isSecondSubmit = false;
        }
      } else {
        this.setData({
          openAttr: false
        })
        wx.showModal({
          title: '提示',
          content: '您还不是会员是否前去充值',
          success(res) {
            if(res.confirm){
              wx.redirectTo({
                url: "/pages/ucenter/memberRecharge/memberRecharge?amount=66&disable=true",
              })
            }else{}
          },
          fail(res) {
          }
        })
      }
      }

    }else{

    if (isSecondSubmit == false){
      isSecondSubmit = true;
      var that = this;
      if (this.data.openAttr == false) {
        //打开规格选择窗口
        this.setData({
          openAttr: !this.data.openAttr,
          disabled: false,
          dis: true,
        });
      } else {
        isSecondSubmit = false;
        //提示选择完整规格
        if (!this.isCheckedAllSpec()) {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: '请选择完整规格'
          });
          this.setData({
            openAttr: !this.data.openAttr,
            disabled: false,
            dis: true,
          });
          return false;
        }

        //根据选中的规格，判断是否有对应的sku信息
        let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
        if (!checkedProductArray || checkedProductArray.length <= 0) {
          //找不到对应的product信息，提示没有库存
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: '没有库存'
          });
          return false;
        }

        let checkedProduct = checkedProductArray[0];
        //验证库存
        if (checkedProduct.number <= 0) {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: '没有库存'
          });
          return false;
        } else if (checkedProduct.number < this.data.number) {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: '库存不足'
          });
          return false;
        }

        //立即购买
        let data = [];
        var goods = this.data.goods;
        goods.isSelect = false;
        var goodsId = this.data.goods.id;
        //添加的商品数量
        var goodsnumber = this.data.number;
        goods.number = goodsnumber;
        var productId = checkedProduct.id;
        var name = this.data.goods.name;
        goods.productId = productId
        // 积分
        goods.integral = checkedProduct.integral
        goods.retailPrice = checkedProduct.price
        goods.priceFlag = checkedProduct.priceFlag
        goods.goodsName = name;
        
        goods.specifications = this.data.checkedSpecText
        goods.checked = true
        if (name.length > 22) {
          goods.goodsName = name.substring(0, 22) + '...';
        }

        wx.setStorageSync('cartflag', 1);
        data.push(goods);
        wx.setStorageSync('cartOne', data)
        try {
          // wx.setStorageSync('cartId', res.data);
          if (app.globalData.hasLogin) {
            if (this.data.mobile == "" || this.data.mobile == undefined) {
              wx.redirectTo({
                url: "/pages/auth/bindMobile/bindMobile"
              });
            } else {
              wx.navigateTo({
                url: '/pages/checkout/checkout'
              })
            }
          } else {
            wx.navigateTo({
              url: "/pages/auth/login/login"
            });
          }
        } catch (e) { }


        // util.request(api.CartFastAdd, {
        //     goodsId: this.data.goods.id,
        //     number: this.data.number,
        //     productId: checkedProduct.id
        //   }, "POST")
        //   .then(function(res) {
        //     if (res.errno == 0) {

        //       // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
        //       try {
        //         wx.setStorageSync('cartId', res.data);
        //         wx.navigateTo({
        //           url: '/pages/checkout/checkout'
        //         })
        //       } catch (e) {}

        //     } else {
        //       wx.showToast({
        //         image: '/static/images/icon_error.png',
        //         title: res.errmsg,
        //         mask: true
        //       });
        //     }
        //   });
      }
      isSecondSubmit = false;
    }
    }
  },
  goLogin() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },
  addToCart: function() {
    var that = this;
    let categoryId = that.data.goods.categoryId
    var pids = app.globalData.memberGoodsNum
    
    if (pids.indexOf(categoryId) != -1){
      var loginType = app.globalData.hasLogin
      if(loginType == false){
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
      }else{
      
        var memberType = that.data.memberType;
        
        // console.log(memberType+"membertype")
      if(memberType == true){
        this.setData({
          disabled: !this.data.disabled,
          color: '',
          dis: false,
        });

        if (this.data.openAttr == false) {
          //打开规格选择窗口
          this.setData({
            openAttr: !this.data.openAttr
          });
        } else {

          //提示选择完整规格
          if (!this.isCheckedAllSpec()) {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: '请选择完整规格'
            });
            return false;
          }

          //根据选中的规格，判断是否有对应的sku信息
          let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
          if (!checkedProductArray || checkedProductArray.length <= 0) {
            //找不到对应的product信息，提示没有库存
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: '没有库存'
            });
            return false;
          }

          let checkedProduct = checkedProductArray[0];
          //验证库存
          if (checkedProduct.number <= 0) {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: '没有库存'
            });
            return false;
          } else if (checkedProduct.number < this.data.number) {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: '库存不足'
            });
            return false;
          }
          if (app.globalData.hasLogin) {
            if (this.data.mobile == "" || this.data.mobile == undefined) {
              wx.redirectTo({
                url: "/pages/auth/bindMobile/bindMobile"
              });
              return false;
            }
          } else {
            wx.navigateTo({
              url: "/pages/auth/login/login"
            });
            return false;
          }
          //添加到购物车
          var goods = this.data.goods;
          goods.isSelect = false;
          var goodsId = this.data.goods.id;
          //添加的商品数量
          var goodsnumber = this.data.number;
          goods.number = goodsnumber;
          var productId = checkedProduct.id;
          goods.integral = checkedProduct.integral
          goods.retailPrice = checkedProduct.price
          var name = this.data.goods.name;
          goods.productId = productId
          goods.specifications = this.data.checkedSpecText
          goods.goodsName = name;
          goods.deleted = false;
          // 获取购物车的缓存数组（没有数据，则赋予一个空数组） 
          var arr = wx.getStorageSync('cart') || [];
          if (arr.length > 0) {
            // 遍历购物车数组  
            for (var j in arr) {
              // 判断购物车内的item的id，和事件传递过来的id，是否相等  
              if (arr[j].id == goodsId && arr[j].productId == productId) {
                // 相等的话，给count+1（即再次添加入购物车，数量+1）  
                arr[j].number = arr[j].number + goodsnumber;
                // 最后，把购物车数据，存放入缓存（此处不用再给购物车数组push元素进去，因为这个是购物车有的，直接更新当前数组即可）  
                try {
                  wx.setStorageSync('cart', arr)
                } catch (e) {
                  console.log(e)
                }
                //关闭窗口
                wx.showToast({
                  title: '加入购物车成功',
                  icon: 'success',
                  duration: 2000
                });
                var count = 0;
                for (var i = 0; i < arr.length; i++) {

                  count += arr[i].number

                }
                that.setData({
                  openAttr: !that.data.openAttr,
                  cartGoodsCount: count,
                  disabled: false
                });
                if (that.data.userHasCollect == 1) {
                  that.setData({
                    collectImage: that.data.hasCollectImage
                  });
                } else {
                  that.setData({
                    collectImage: that.data.noCollectImage
                  });
                }
                // 返回（在if内使用return，跳出循环节约运算，节约性能） 
                return;
              }
            }
            // 遍历完购物车后，没有对应的item项，把goodslist的当前项放入购物车数组  
            goods.checked = true
            arr.push(goods);
          } else {
            goods.checked = true
            arr.push(goods);
          }
          try {
            wx.setStorageSync('cart', arr)
            // 返回（在if内使用return，跳出循环节约运算，节约性能） 
            //关闭窗口
            // wx.showToast({
            //   title: '加入购物车成功！',
            //   icon: 'success',
            //   duration: 2000
            // });
            // let _res = res;
            // if (_res.errno == 0) {
            var count = 0;
            for (var i = 0; i < arr.length; i++) {

              count += arr[i].number

            }


            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000
            });
            that.setData({
              openAttr: !that.data.openAttr,
              cartGoodsCount: count,
              disabled: false
            });
            if (that.data.userHasCollect == 1) {
              that.setData({
                collectImage: that.data.hasCollectImage
              });
            } else {
              that.setData({
                collectImage: that.data.noCollectImage
              });
            }
            // } else {
            //   wx.showToast({
            //     image: '/static/images/icon_error.png',
            //     title: _res.errmsg,
            //     mask: true,

            //   });
            // }

          } catch (e) {
            console.log(e)
          }

          // util.request(api.CartAdd, {
          //     goodsId: this.data.goods.id,
          //     number: this.data.number,
          //     productId: checkedProduct.id
          //   }, "POST")
          //   .then(function(res) {
          //     let _res = res;
          //     if (_res.errno == 0) {
          //       wx.showToast({
          //         title: '添加成功'
          //       });
          //       that.setData({
          //         openAttr: !that.data.openAttr,
          //         cartGoodsCount: _res.data,
          //         disabled: false
          //       });
          //       if (that.data.userHasCollect == 1) {
          //         that.setData({
          //           collectImage: that.data.hasCollectImage
          //         });
          //       } else {
          //         that.setData({
          //           collectImage: that.data.noCollectImage
          //         });
          //       }
          //     } else {
          //       wx.showToast({
          //         image: '/static/images/icon_error.png',
          //         title: _res.errmsg,
          //         mask: true,

          //       });
          //     }

          //   });
        } 
      }else{
        this.setData({
          openAttr: false
        })
        wx.showModal({
          title: '提示',
          content: '您还不是会员是否前去充值',
          success(res) {
            if(res.confirm){
              wx.redirectTo({
                url: "/pages/ucenter/memberRecharge/memberRecharge?amount=66&disable=true",
              })
            }else{}
          },
        })
      }
      }   
    }else{
      
    
    this.setData({
      disabled: !this.data.disabled,
      color: '',
      dis: false,
    });
    
    if (this.data.openAttr == false) {
      //打开规格选择窗口
      this.setData({
        openAttr: !this.data.openAttr
      });
    } else {

      //提示选择完整规格
      if (!this.isCheckedAllSpec()) {
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '请选择完整规格'
        });
        return false;
      }

      //根据选中的规格，判断是否有对应的sku信息
      let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());
      if (!checkedProductArray || checkedProductArray.length <= 0) {
        //找不到对应的product信息，提示没有库存
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '没有库存'
        });
        return false;
      }

      let checkedProduct = checkedProductArray[0];
      //验证库存
      if (checkedProduct.number <= 0) {
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '没有库存'
        });
        return false;
      } else if (checkedProduct.number < this.data.number){
        wx.showToast({
          image: '/static/images/icon_error.png',
          title: '库存不足'
        });
        return false;
      }
      if (app.globalData.hasLogin) {
        if (this.data.mobile == "" || this.data.mobile == undefined) {
          wx.redirectTo({
            url: "/pages/auth/bindMobile/bindMobile"
          });
          return false;
        }
      } else {
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return false;
      }
      //添加到购物车
      var goods = this.data.goods;
      goods.isSelect = false;
      var goodsId = this.data.goods.id;
      //添加的商品数量
      var goodsnumber = this.data.number;
      goods.number = goodsnumber;
      var productId = checkedProduct.id;
      goods.integral = checkedProduct.integral
      goods.retailPrice = checkedProduct.price
      var name = this.data.goods.name;
      goods.productId = productId
      goods.specifications = this.data.checkedSpecText
      goods.goodsName = name;
      goods.deleted = false;
      // 获取购物车的缓存数组（没有数据，则赋予一个空数组） 
      var arr = wx.getStorageSync('cart') || [];    
      // console.log("arr,{}", arr);  
       if (arr.length > 0) {
        // 遍历购物车数组  
        for (var j in arr) {
          // 判断购物车内的item的id，和事件传递过来的id，是否相等  
          if (arr[j].id == goodsId && arr[j].productId == productId) {
            // 相等的话，给count+1（即再次添加入购物车，数量+1）  
            arr[j].number = arr[j].number + goodsnumber;
            // 最后，把购物车数据，存放入缓存（此处不用再给购物车数组push元素进去，因为这个是购物车有的，直接更新当前数组即可）  
            try {
              wx.setStorageSync('cart', arr)
            } catch (e) {
              console.log(e)
            }
            //关闭窗口
            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000
            });
            var count = 0;
            for (var i = 0; i < arr.length; i++) {

              count += arr[i].number

            }
            that.setData({
              openAttr: !that.data.openAttr,
              cartGoodsCount: count,
              disabled: false
            });
            if (that.data.userHasCollect == 1) {
              that.setData({
                collectImage: that.data.hasCollectImage
              });
            } else {
              that.setData({
                collectImage: that.data.noCollectImage
              });
            }
            // 返回（在if内使用return，跳出循环节约运算，节约性能） 
            return;
          }
        }
        // 遍历完购物车后，没有对应的item项，把goodslist的当前项放入购物车数组  
         goods.checked = true
        arr.push(goods);
      } else {
         goods.checked = true
        arr.push(goods);
      }
      try {
        wx.setStorageSync('cart', arr)
        // 返回（在if内使用return，跳出循环节约运算，节约性能） 
        //关闭窗口
        // wx.showToast({
        //   title: '加入购物车成功！',
        //   icon: 'success',
        //   duration: 2000
        // });
        // let _res = res;
        // if (_res.errno == 0) {
        var count = 0;
        for (var i = 0;i<arr.length;i++){
          
          count += arr[i].number

        }


            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
               duration: 2000
            });
            that.setData({
              openAttr: !that.data.openAttr,
              cartGoodsCount: count,
              disabled: false
            });
            if (that.data.userHasCollect == 1) {
              that.setData({
                collectImage: that.data.hasCollectImage
              });
            } else {
              that.setData({
                collectImage: that.data.noCollectImage
              });
            }
          // } else {
          //   wx.showToast({
          //     image: '/static/images/icon_error.png',
          //     title: _res.errmsg,
          //     mask: true,

          //   });
          // }

      } catch (e) {
        console.log(e)
      }

      // util.request(api.CartAdd, {
      //     goodsId: this.data.goods.id,
      //     number: this.data.number,
      //     productId: checkedProduct.id
      //   }, "POST")
      //   .then(function(res) {
      //     let _res = res;
      //     if (_res.errno == 0) {
      //       wx.showToast({
      //         title: '添加成功'
      //       });
      //       that.setData({
      //         openAttr: !that.data.openAttr,
      //         cartGoodsCount: _res.data,
      //         disabled: false
      //       });
      //       if (that.data.userHasCollect == 1) {
      //         that.setData({
      //           collectImage: that.data.hasCollectImage
      //         });
      //       } else {
      //         that.setData({
      //           collectImage: that.data.noCollectImage
      //         });
      //       }
      //     } else {
      //       wx.showToast({
      //         image: '/static/images/icon_error.png',
      //         title: _res.errmsg,
      //         mask: true,
              
      //       });
      //     }

      //   });
    }
    }
    
  },
  cutNumber: function() {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },
  addNumber: function() {
    this.setData({
      number: this.data.number + 1
    });
  },
  changeNumber: function(event) {
    this.setData({
      number: parseInt(event.detail.value) > 1 ? parseInt(event.detail.value) : 1
    });
  }
})